package edu.gyc.security.controller;

import edu.gyc.security.model.FileInfo;
import org.apache.tomcat.util.http.fileupload.IOUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Date;

@RestController
@RequestMapping("/file")
public class FileController {
  static   String folder="/Users/Apple/Desktop/codes/security-master/security/src/main/java/edu/gyc/security/controller";
    @PostMapping("/upload")
    public FileInfo upload(MultipartFile pic) throws Exception{
        System.out.println(pic.getName());
        System.out.println(pic.getSize());
        System.out.println(pic.getOriginalFilename());


        File localFile = new File(folder, new Date().getTime() + ".jpg");
        pic.transferTo(localFile);
        return new FileInfo(localFile.getAbsolutePath());
    }

    @GetMapping("/{id}")
    public void download(@PathVariable String id, HttpServletRequest request, HttpServletResponse response)throws Exception{
        try (InputStream inputStream = new FileInputStream(new File(folder, id + ".jpg"));
             OutputStream outputStream = response.getOutputStream();) {

            response.setContentType("application/x-download");
            response.addHeader("Content-Disposition", "attachment;filename=test.jpg");

            IOUtils.copy(inputStream, outputStream);
            outputStream.flush();
        }
    }
}
